package cn.edu.imut.dao;

import cn.edu.imut.bean.AdminBean;
import cn.edu.imut.bean.ProductBean;
import cn.edu.imut.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class AdminDao {
    private final ProductDao productDao = new ProductDao();
    /**
     * 管理员登录
     */
    public AdminBean login(String username, String password) {
        String sql = "SELECT * FROM gs_admins WHERE username = ? AND password = ?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            ResultSet rs = pstmt.executeQuery();

            if (rs.next()) {
                return new AdminBean(
                        rs.getInt("admin_id"),
                        rs.getString("username"),
                        rs.getString("password")
                );
            }
        } catch (Exception e) {
            System.err.println("管理员登录失败：" + e.getMessage());
        }
        return null;
    }
    /**
     * 添加新商品
     */
    public void addNewProduct() {
        Scanner sc = new Scanner(System.in);

        try {
            // 输入商品信息
            System.out.println("请输入商品名称：");
            String name = sc.nextLine();

            System.out.println("请输入分类 ID：");
            int categoryId = sc.nextInt();

            System.out.println("请输入商品价格：");
            double price = sc.nextDouble();

            System.out.println("请输入商品库存：");
            int stock = sc.nextInt();

            // 验证分类 ID 是否有效
            if (!productDao.isValidCategoryId(categoryId)) {
                System.out.println("无效的分类 ID，请检查分类是否存在！");
                return;
            }

            // 调用 DAO 插入新商品
            boolean success = productDao.addNewProduct(name, categoryId, price, stock);

            if (success) {
                System.out.println("商品添加成功！");
            } else {
                System.out.println("商品添加失败，请重试！");
            }
        } catch (Exception e) {
            System.err.println("添加新商品时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     * 添加新商品
     */
    public boolean addNewProduct(ProductBean product) {
        String sql = "INSERT INTO gs_products (product_name, product_category, price, stock) VALUES (?, ?, ?, ?)";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, product.getProductName());
            pstmt.setInt(2, product.getCategoryId());
            pstmt.setDouble(3, product.getPrice());
            pstmt.setInt(4, product.getStock());
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            System.err.println("添加新商品时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 下架商品
     */
    public boolean removeProduct(int productId) {
        String sql = "DELETE FROM gs_products WHERE product_id = ?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, productId);
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            System.err.println("下架商品时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 编辑商品信息
     */
    public boolean updateProductInfo(int productId, String newName, double newPrice) {
        String sql = "UPDATE gs_products SET product_name = ?, price = ? WHERE product_id = ?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, newName);
            pstmt.setDouble(2, newPrice);
            pstmt.setInt(3, productId);
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            System.err.println("编辑商品信息时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 查询所有商品库存
     */
    public List<ProductBean> getAllStock() {
        List<ProductBean> products = new ArrayList<>();
        String sql = "SELECT p.*, c.category_name FROM gs_products p "
                + "LEFT JOIN gs_categories c ON p.product_category = c.category_id";

        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                products.add(new ProductBean(
                        rs.getInt("product_id"),        // 商品ID
                        rs.getString("product_name"),  // 商品名称
                        rs.getInt("product_category"), // 商品分类ID
                        rs.getString("category_name"), // 分类名称
                        rs.getInt("sales"),            // 销量
                        rs.getDouble("price"),         // 商品价格
                        rs.getInt("stock")             // 商品库存
                ));
            }
        } catch (Exception e) {
            System.err.println("查询所有商品库存时发生错误：" + e.getMessage());
            e.printStackTrace();
        }

        return products;
    }


    /**
     * 调整商品库存
     */
    public boolean updateStock(int productId, int newStock) {
        String sql = "UPDATE gs_products SET stock = ? WHERE product_id = ?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, newStock);
            pstmt.setInt(2, productId);
            return pstmt.executeUpdate() > 0;
        } catch (Exception e) {
            System.err.println("调整商品库存时发生错误：" + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 查询库存低于阈值的商品
     */
    public List<ProductBean> getProductsBelowThreshold(int threshold) {
        List<ProductBean> lowStockProducts = new ArrayList<>();

        // 检查输入阈值是否合法
        if (threshold <= 0) {
            System.out.println("库存阈值必须是正整数！");
            return lowStockProducts;
        }

        // SQL 查询语句，包含分类名称关联
        String sql = "SELECT p.*, c.category_name FROM gs_products p " +
                "LEFT JOIN gs_categories c ON p.product_category = c.category_id " +
                "WHERE p.stock < ?";

        try (Connection connection = DBUtil.getConnection();
             PreparedStatement pstmt = connection.prepareStatement(sql)) {

            pstmt.setInt(1, threshold); // 设置库存阈值参数
            ResultSet rs = pstmt.executeQuery();

            while (rs.next()) {
                // 将查询结果映射到 ProductBean 对象
                lowStockProducts.add(new ProductBean(
                        rs.getInt("product_id"),        // 商品ID
                        rs.getString("product_name"),  // 商品名称
                        rs.getInt("product_category"), // 分类ID
                        rs.getString("category_name"), // 分类名称
                        rs.getInt("sales"),            // 销量
                        rs.getDouble("price"),         // 商品价格
                        rs.getInt("stock")             // 商品库存
                ));
            }
        } catch (Exception e) {
            System.err.println("查询低库存商品时发生错误：" + e.getMessage());
            e.printStackTrace();
        }

        // 如果查询结果为空，打印提示信息
        if (lowStockProducts.isEmpty()) {
            System.out.println("没有商品的库存低于设定的阈值（" + threshold + "）。");
        }

        return lowStockProducts;
    }

}
